package cn.e3mall.manager.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.utils.IDUtils;
import cn.e3mall.manager.service.ItemService;
import cn.e3mall.mapper.TbItemDescMapper;
import cn.e3mall.pojo.TbItemDesc;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.e3mall.common.pojo.EasyUIDataGridResult;
import cn.e3mall.mapper.TbItemMapper;
import cn.e3mall.pojo.TbItem;
import cn.e3mall.pojo.TbItemExample;
import cn.e3mall.pojo.TbItemExample.Criteria;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.*;


/**
 * 商品管理Service
 * <p>Title: ItemServiceImpl</p>
 * <p>Description: </p>
 * <p>personal</p>
 * @version 1.0
 */
@Service
@Transactional
public class ItemServiceImpl implements ItemService {

	private final Logger logger = LoggerFactory.getLogger(ItemServiceImpl.class);

	@Autowired
	private TbItemMapper itemMapper;
	@Autowired
	private TbItemDescMapper tbItemDescMapper;
	@Autowired
	private JmsTemplate jmsTemplate;
	@Resource
	private Destination topicDestination;
	@Autowired
	private JedisClient jedisClient;

	@Value("${redis.item}")
	private String exitem;
	@Value("${redis.item.expire}")
	private Integer expireTIme;

	@Override
	public TbItem getItemById(long itemId) {
        try{
			String s = jedisClient.get(exitem+":"+itemId+":BASE");
			if(!StringUtils.isNullOrEmpty(s)){
				logger.info("查询到商品缓存数据");
				TbItem tbItem = JSONObject.parseObject(s, TbItem.class);
				return tbItem;
			}
		}catch (Exception e){
             logger.warn("缓存中无数据或者查询失败");
		}
		//根据主键查询
		//TbItem tbItem = itemMapper.selectByPrimaryKey(itemId);
		TbItemExample example = new TbItemExample();
		Criteria criteria = example.createCriteria();
		//设置查询条件
		criteria.andIdEqualTo(itemId);
		//执行查询
		List<TbItem> list = itemMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			logger.info("添加商品缓存");
			try{
				jedisClient.set(exitem+":"+itemId+":BASE",JSONObject.toJSONString(list.get(0)));
				//设置过期时间(s)
				jedisClient.expire(exitem+":"+itemId+":BASE",expireTIme);
			}catch (Exception e){
				logger.warn("添加缓存失败");
			}
			return list.get(0);
		}
		return null;
	}

	@Override
	public EasyUIDataGridResult getItemList(int page, int rows) {
		//设置分页信息
		PageHelper.startPage(page, rows);

		//执行查询
		TbItemExample example = new TbItemExample();
		List<TbItem> list = itemMapper.selectByExample(example);
		//创建一个返回值对象
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		result.setRows(list);
		//取分页结果
		PageInfo<TbItem> pageInfo = new PageInfo<>(list);
		//取总记录数
		long total = pageInfo.getTotal();
		result.setTotal(total);
		return result;
	}

	@Override
	public void save(Map<String, String> map) {
		final long genItemId = IDUtils.genItemId();
		String desc =  map.get("desc");
		TbItem tbItem =new TbItem();
		tbItem.setCid( Long.valueOf( map.get( "cid" ) ) );
		tbItem.setTitle(  map.get( "title" ) );
		tbItem.setSellPoint( map.get( "sellPoint" )  );
		tbItem.setPrice( Long.valueOf( map.get( "price" ) ) );
		tbItem.setNum( Integer.valueOf( map.get( "num" ) ) );
		tbItem.setBarcode( map.get( "barcode" )  );
		tbItem.setImage( map.get( "image" )  );
		tbItem.setImage( map.get( "image" )  );
		tbItem.setId( genItemId );
		//1正常，2下架，3删除
		tbItem.setStatus( (byte) 1 );
		tbItem.setCreated( new Date(  ) );
		tbItem.setUpdated( new Date(  ) );
		itemMapper.insert( tbItem );
		TbItemDesc tbItemDesc = new TbItemDesc();
		tbItemDesc.setItemId( genItemId );
		tbItemDesc.setUpdated( new Date(  ) );
		tbItemDesc.setCreated( new Date(  ) );
		tbItemDesc.setItemDesc( desc );
		tbItemDescMapper.insert( tbItemDesc);

		jmsTemplate.send(topicDestination, new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				TextMessage textMessage = session.createTextMessage(genItemId + "");
				return textMessage;
			}
		});

	}

	@Override
	public TbItemDesc findDesc(Long itemId) {
		try{
			String s = jedisClient.get(exitem+":"+itemId+":DESC");
			if(!StringUtils.isNullOrEmpty(s)){
				logger.info("查询到商品描述缓存数据");
				TbItemDesc tbItemDesc = JSONObject.parseObject(s, TbItemDesc.class);
				return tbItemDesc;
			}
		}catch (Exception e){
			logger.warn("缓存中无数据或者查询失败");
		}
		TbItemDesc tbItemDesc = tbItemDescMapper.selectByPrimaryKey( itemId );
		logger.info("添加商品描述缓存");
		try{
			jedisClient.set(exitem+":"+itemId+":DESC",JSONObject.toJSONString(tbItemDesc));
			//设置过期时间(s)
			jedisClient.expire(exitem+":"+itemId+":DESC",expireTIme);
		}catch (Exception e){
			logger.warn("添加缓存失败");
		}
		return tbItemDesc;
	}

}
